package com.javabaas.server.novel_server.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.javabaas.server.novel_server.common.Constant;
import com.javabaas.server.novel_server.common.StatusCode;
import org.apache.log4j.Logger;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class AuthInterceptor implements HandlerInterceptor {

    private static Logger logger = Logger.getLogger(HandlerInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        String sign = httpServletRequest.getParameter("sign");

        //对sign做校验，如果验证不通过报SC_UNAUTHORIZED，否则验证通过
        if (!validSign(httpServletRequest, sign)) {
            authError(httpServletResponse);
            return false;
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }


    /**
     * 校验sign
     * */
    private boolean validSign(HttpServletRequest httpRequest, String sign) {
        if (StringUtils.isEmpty(sign)) {
            logger.info("clent sign is null");
            return false;
        }
        String query = null;


        if (httpRequest.getQueryString().endsWith(sign) && httpRequest.getQueryString().length() > 37) {
            query = httpRequest.getQueryString().replaceAll("&sign=.{32}", "");
        }else if (httpRequest.getQueryString().endsWith(sign) && httpRequest.getQueryString().length() <= 37) {
            query = httpRequest.getQueryString().replaceAll("sign=.{32}", "");
        }else {
            query = httpRequest.getQueryString().replaceAll("sign=.{33}", "");
        }
        String server_sign = httpRequest.getMethod() + "_" + query + "_" + Constant.salt;
        String server_md5_sign = DigestUtils.md5DigestAsHex(server_sign.getBytes());
        logger.info("client sign --> " + sign + ", server sign --> " + server_md5_sign + ", 原始串 --> " + server_sign);
        return server_md5_sign.equalsIgnoreCase(sign);
    }

    /**
     * 处理sign错误的返回
     * */
    private void authError(HttpServletResponse httpResponse) throws IOException {
        httpResponse.setCharacterEncoding("UTF-8");
        httpResponse.setContentType("application/json; charset=utf-8");
        httpResponse.setStatus(StatusCode.STATUS_SC_UNAUTHORIZED.getCode());
        Map map = new HashMap();
        map.put("code", StatusCode.STATUS_SC_UNAUTHORIZED.getCode());
        map.put("msg", StatusCode.STATUS_SC_UNAUTHORIZED.getMsg());
        ObjectMapper mapper = new ObjectMapper();
        httpResponse.getWriter().write(mapper.writeValueAsString(map));
    }
}
